package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {
    @Autowired
    private ModuleService moduleService;

    @Autowired
    private UserService userService;

    @Override
    // Authentication 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取令牌对象
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        // 获取页面中的email和password
        String email = token.getUsername();
        char[] charPwd = token.getPassword();
        String password = new String(charPwd);

        User user = userService.findByEmail(email);
        if (user != null) {
            String password_db = user.getPassword();
            if (password_db.equals(password)) {
                return new SimpleAuthenticationInfo(user, password_db, getName());
            }
        }
        return null;
    }

    @Override
    // Authorization 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取当前登录用户对象
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<Module> moduleList = moduleService.findModulesByUser(user);

        // 创建授权信息对象
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        // 添加权限
        for (Module module : moduleList) {
            authorizationInfo.addStringPermission(module.getCpermission());
        }
        return authorizationInfo;
    }
}
